'use strict';
const BaseService = require('../../libs/base/BaseService');
const Player = require('./manager/player');
/**
 * Gateway服务，负责管理系统的数据对接
 */
class Gateway extends BaseService {
  /**Gateway
   * 构造函数
   */
  constructor() {
    super('Gateway');
    this.connections = new Map();
    this.playerCount = 0;
  }
  /**
   * 初始化服务
   */
  async init() {
    console.log('[Gateway] 服务初始化完成');
  }

  /**
   * 处理新的连接
   * @param {object} socket Socket连接对象
   */
  handleConnection(socket) {
    try {
      const playerId = this._generatePlayerId();
      const player = new Player(playerId, socket);

      // 存储连接
      this.connections.set(playerId, player);
      this.playerCount++;

      console.log(`[Gateway] 新连接建立 playerId=${playerId}`);

      // 设置事件处理器
      this._setupSocketHandlers(socket, player);

    } catch (error) {
      console.error('[Gateway] 处理新连接失败:', error);
      socket.disconnect(true);
    }
  }

  /**
   * 设置Socket事件处理器
   * @param {object} socket Socket连接对象
   * @param {Player} player 玩家对象
   * @private
   */
  _setupSocketHandlers(socket, player) {
    // 登录请求
    socket.on('login', async (data) => {
      try {
        const success = await player.validateLogin(data);

        if (success) {
          socket.emit('loginResponse', {
            success: true,
            playerId: player.id,
            sessionId: player.sessionId
          });
          console.log(`[Gateway] 玩家登录成功 playerId=${player.id}`);
        } else {
          socket.emit('loginResponse', {
            success: false,
            message: '登录失败：用户名或密码错误'
          });
        }
      } catch (error) {
        console.error('[Gateway] 处理登录请求失败:', error);
        socket.emit('loginResponse', {
          success: false,
          message: '登录失败：服务器错误'
        });
      }
    });

    // 心跳包
    socket.on('heartbeat', () => {
      player.updateLastActiveTime();
      socket.emit('heartbeatResponse', { timestamp: Date.now() });
    });

    // 断开连接
    socket.on('disconnect', () => {
      this.handleDisconnect(player.id);
    });

    // 错误处理
    socket.on('error', (error) => {
      console.error(`[Gateway] Socket错误 playerId=${player.id}:`, error);
      this.handleDisconnect(player.id);
    });
  }

  /**
   * 处理断开连接
   * @param {string} playerId 玩家ID
   */
  handleDisconnect(playerId) {
    try {
      const player = this.connections.get(playerId);
      if (player) {
        player.disconnect();
        this.connections.delete(playerId);
        this.playerCount--;
        console.log(`[Gateway] 连接断开 playerId=${playerId}`);
      }
    } catch (error) {
      console.error('[Gateway] 处理断开连接失败:', error);
    }
  }

  /**
   * 获取在线玩家数量
   * @returns {number} 在线玩家数量
   */
  getOnlineCount() {
    return this.playerCount;
  }

  /**
   * 获取玩家连接
   * @param {string} playerId 玩家ID
   * @returns {Player|null} 玩家对象
   */
  getPlayerConnection(playerId) {
    return this.connections.get(playerId) || null;
  }

  /**
   * 生成玩家ID
   * @returns {string} 玩家ID
   * @private
   */
  _generatePlayerId() {
    return `player_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  }

  /**
   * 广播消息给所有已登录的玩家
   * @param {string} event 事件名称
   * @param {object} data 消息数据
   */
  broadcast(event, data) {
    for (const player of this.connections.values()) {
      if (player.isLoggedIn) {
        player.send(event, data);
      }
    }
  }
}

module.exports = Gateway; 